<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            @change="changePlant(searchParam.plantId)"
            filterable
          >
            <el-option
              v-for="plant in plantList"
              :key="plant.id"
              :label="plant.organizationCode"
              :value="plant.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            clearable
            filterable
            @change="changeWorkCenter(searchParam.workCenterId)"
          >
            <el-option
              v-for="item in workCenterValue"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="加工单">
          <el-select
            v-model="searchParam.workOrderId"
            placeholder="请选择工作中心"
            clearable
            filterable
          >
            <el-option
              v-for="item in workOrderList"
              :key="item.id"
              :label="`${item.workOrderCode}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >-->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工作中心"
          prop="workCenterCode"
          min-width="230"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span>
              {{ scope.row.workCenterCode }}-{{ scope.row.workCenterName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="加工单"
          prop="workOrderCode"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="计划数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="已完成数量"
          prop="planFinishQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="年份"
          prop="planYear"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="周数"
          prop="planWeek"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="派工单"
          prop="workingFormCode"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="计划数量"
          prop="workingPlanQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="已完成数量"
          prop="workingPlanFinishQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="合格数量"
          prop="validQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="不合格数量"
          prop="invalidQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="班次名称"
          prop="shiftName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="报工数量"
          prop="reportQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="是否合格"
          prop="isValid"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.isValid === 1">合格</span>
            <span v-else>不合格</span>
          </template>
        </el-table-column>
        <el-table-column
          label="报工状态"
          prop="reportState"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.reportState === 1">提交</span>
            <span v-else>新建</span>
          </template>
        </el-table-column>
        <el-table-column
          label="开始时间"
          prop="startTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="完工时间"
          prop="completeTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建名"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="修改名"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              :disabled="scope.row.reportState == 1"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="submit(scope.row)"
              :disabled="scope.row.reportState == 1"
              >提交</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              v-if="scope.row.reportState == 0"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesvirtualplanreport-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESVIRTUALPLANREPORT",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesvirtualplanreport/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  workCenterId: "",
  workOrderId: "",
};

const deleteParam = {
  api: "/mes/mesvirtualplanreport/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlantList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesvirtualplanreport/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开虚拟计划填报表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改虚拟计划填报";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增虚拟计划填报";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开虚拟计划填报表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "虚拟计划填报详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesvirtualplanreport/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
  searchParam.value.plantId = plantList.value[0].id;
  changePlant(searchParam.plantId);
};
const changePlant = (id) => {
  workCenterValue.value = [];
  workCenterList(id);
};
// 根据工厂id 查询中心
const workCenterValue: any = ref([]);
const workCenterList = async (id) => {
  if (id != "") {
    const res2: any = await request({
      url: `/mes/mesworkshop/getList`,
      method: "post",
      data: { enabled: 1, plantId: id },
    });
    workCenterValue.value = res2.data;
  } else {
    workCenterValue.value = [];
  }
};
/** 选择工厂时触发 根据Code赋值Id*/
const changeWorkCenter = (id: string) => {
  workOrderList.value = [];
  getWorkOrderList(id);
};

// 加工单
const workOrderList: any = ref([]);
const getWorkOrderList = async (id: string) => {
  if (id != "") {
    const res: any = await request({
      url: `/mes/mesworkorder/queryByWorkCenter`,
      method: "post",
      data: { workCenterId: id },
    });
    workOrderList.value = res.data;
  } else {
    workOrderList.value = [];
  }
};
onMounted(() => {
  getPlantList();
});

// 提交
const submit = async (row) => {
  ElMessageBox.confirm("确定提交吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      row.reportState = 1;
      const res: any = await request({
        url: "/mes/mesvirtualplanreport/save",
        method: "post",
        data: row,
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "提交成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消停用",
      });
    });
};
</script>
